<?php 
/**
 * 售后单管理
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/lib_goods.php');
@ini_set('display_errors',        2);



    /* 检查权限 */
    admin_priv('order_view');
$step = !empty($_REQUEST['step'])?$_REQUEST['step']:'add';
$smarty->assign('languages', $_LANG);   

/*------------------------------------------------------ */
//-- 售后单列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'sale_list')
{   
    /* 检查权限 */
    admin_priv('back_view');
    $smarty->assign('service_state', $_LANG['st']);   // 售后状态
    $smarty->assign('service_type', $_LANG['ty']);   // 售后类型
    $smarty->assign('handle_state', $_LANG['hst']);   // 处理状态
    $smarty->assign('ur_here',"售后单列表");
    $sale_list=sale_list();//获取售后单列表





    $smarty->assign('full_page',       1);
    $smarty->assign('filter',       $sale_list['filter']);
    $smarty->assign('record_count', $sale_list['record_count']);
    $smarty->assign('page_count',   $sale_list['page_count']);
    $smarty->assign('sale_list',$sale_list['sale_list']);
    $smarty->display('sale/sale_list.htm');
}
//分页
elseif ($_REQUEST['act'] == 'sale_query')
{
    $sale_list = sale_list();//订单列表
    $smarty->assign('filter',       $sale_list['filter']);
    $smarty->assign('record_count', $sale_list['record_count']);
    $smarty->assign('page_count',   $sale_list['page_count']);
    $smarty->assign('sale_list',$sale_list['sale_list']);

    make_json_result($smarty->fetch('sale/sale_list.htm'), '', array('filter' => $sale_list['filter'], 'page_count' => $sale_list['page_count']));

}
//售后单详情况

elseif ($_REQUEST['act'] == 'sale_info') {
    $service_id = !empty($_REQUEST['service_id'])?$_REQUEST['service_id']:'';
    $sale_info  = sale_info($service_id);
    $content    = $_LANG['content'][$sale_info['handle_type']];


    //查询退款单
    $sql = "SELECT * FROM  ".$ecs->table('refund'). "WHERE service_id = $service_id ";
    $refund_list = $db->getAll($sql);

    foreach ($refund_list as $key => $value) {
        $refund_list[$key]['add_time']= date('Y-m-d-H:i:s',$value['add_time']);
        if(!empty($value['confirm_time'])){
          $refund_list[$key]['confirm_time']= date('Y-m-d-H:i:s',$value['confirm_time']);  
        }
        else
        {
          $refund_list[$key]['confirm_time']= "未确认";
        }
    }







    $smarty->assign('refund_list',$refund_list);
    $smarty->assign('content',$content);
    $smarty->assign('sale_info',$sale_info);
    $smarty->display('sale/sale_info.htm');
}

//客服提交售后处理
elseif ($_REQUEST['act'] == 'handle') {
    $handle_type=!empty($_REQUEST['handle_type'])?$_REQUEST['handle_type']:'';//售后类型
    $service_id=!empty($_REQUEST['service_id'])?$_REQUEST['service_id']:'';//售后单ID
    $content = !empty($_REQUEST['content'])?$_REQUEST['content']:'';//说明消息

    //通过审核处理
    if(!empty($_REQUEST['confirm'])){
        //退款不退货
        if($handle_type == '1'){
            $sale_info = sale_info($service_id);
            $refund_reason = $_LANG['refund_reason'][$sale_info['service_type']];//退款理由
            //自动生成退款单
            $refund_info = array(
            'order_sn'          => $sale_info['order_sn'],
            'refund_reason'     => $refund_reason,
            'refund_money'      => $sale_info['refund_money'],
            'add_time'          => time(),
            'handle_user'       => $sale_info['consignee'],
            'service_id'        => $sale_info['service_id'],
            'payment_num'       => $sale_info['payment_num'],
            );
            $db->autoExecute($ecs->table('refund'), $refund_info, 'INSERT', '', 'SILENT'); 
            //更改售后单状态
            $sql =  " UPDATE ".$ecs->table('sale_service').
            " SET handle_state = 6,service_state = 2 ".
            " WHERE service_id = $service_id ";
            $db->query($sql);
            //记录操作
            $handle_record = array(
            'handle_user'       => $_SESSION['admin_name'],
            'service_id'        => $service_id,
            'add_time'          => time(),
            'content'           => $content,
            'handle_id'         => 2,
            );
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
            $links[] = array('href' => 'sale.php?act=sale_list', 'text' => "操作成功");
            sys_msg("操作成功", 100, $links);
        }

        //退款退货
        if($handle_type == '2'){
            
            // 1.自动生成退货单
            $sale_info = sale_info($service_id);
            $order_return_info = array(
            'service_id'        => intval($service_id),
            'is_push'           => 2,
            'order_sn'          => $sale_info['order_sn'],
            'add_time'          => time(),
            'service_type'      => $sale_info['service_type'],
            );

            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_return_info'), $order_return_info, 'INSERT', '', 'SILENT'); 
            $return_id=$db->insert_id();
            //循环商品写入数据表
            foreach ($sale_info['goods'] as $key => $value) {
                $return_goods =  array(
                    'return_id'         => intval($return_id),
                    'goods_id'          => $value['goods_id'],
                    'goods_name'        => $value['goods_name'],
                    'goods_sku'         => $value['goods_sku'],
                    'goods_attr'        => $value['goods_attr'],
                    'goods_attr_sku'    => $value['goods_attr_sku'],
                    'goods_number'      => $value['goods_number'],
                );
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_return_goods'), $return_goods, 'INSERT', '', 'SILENT'); 
            }
        //记录操作
        $handle_record = array(
        'handle_user'       => $_SESSION['admin_name'],
        'service_id'        => $service_id,
        'add_time'          => time(),
        'confirm_time'      => time(),
        'content'           => $content,
        'handle_id'         => 2,
        );
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
        //更新售后状态
        $sql = " UPDATE ".$GLOBALS['ecs']->table('sale_service') .
               " SET service_state = 2 ,handle_state = 5 ".
               " WHERE service_id = $service_id";
        $db->query($sql);



        $links[] = array('href' => 'sale.php?act=sale_list', 'text' => "操作成功");
        sys_msg("操作成功", 100, $links);





        }




    }
    //审核不通过处理
    if(!empty($_REQUEST['cancel'])){
        $sale_info = sale_info($service_id);
        //循环商品标记为未售后
        $where="";
        foreach ($sale_info['goods'] as $key => $value) {
             $where = " rec_id = ".$value['rec_id']." OR ".$where;
        }
        $where =substr($where,0,-3); 
        $sql =  " UPDATE ".$ecs->table('order_goods').
            " SET is_sale = 0 ".
            " WHERE ".$where;
        $db->query($sql);
        //更改售后单状态
        $sql =  " UPDATE ".$ecs->table('sale_service').
                " SET service_state = 3 ,handle_state =2 ".
                " WHERE service_id =$service_id";
        $db->query($sql);
        //记录操作
        $handle_record = array(
        'handle_user'       => $_SESSION['admin_name'],
        'service_id'        => $service_id,
        'add_time'          => time(),
        'content'           => $content,
        'handle_id'         => 2,
        );
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
        $links[] = array('href' => 'sale.php?act=sale_list', 'text' => "操作成功");
        sys_msg("操作成功", 100, $links);
    }
    //退运费处理
    if(!empty($_REQUEST['refund'])){
        $refund_money = !empty($_REQUEST['refund_money'])?$_REQUEST['refund_money']:'';
        $sale_info = sale_info($service_id);


        $refund_reason = "运费";//退款理由
        //自动生成退款单
        $refund_info = array(
        'order_sn'          => $sale_info['order_sn'],
        'refund_reason'     => $refund_reason,
        'refund_money'      => $refund_money,
        'add_time'          => time(),
        'handle_user'       => $sale_info['consignee'],
        'service_id'        => $sale_info['service_id'],
        'payment_num'       => $sale_info['payment_num'],
        'refund_type'       => 2,
        'refund_stat'       => 2,
        );
        $db->autoExecute($ecs->table('refund'), $refund_info, 'INSERT', '', 'SILENT'); 
        $content = "已将运费:".$refund_money."元退款到你填写的账号中";
        //记录操作
        $handle_record = array(
        'handle_user'       => $_SESSION['admin_name'],
        'service_id'        => $service_id,
        'add_time'          => time(),
        'content'           => $content,
        'handle_id'         => 2,
        );
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
        $links[] = array('href' => 'sale.php?act=sale_list', 'text' => "操作成功");
        sys_msg("操作成功", 100, $links);
    }
    //取消售后
    if(!empty($_REQUEST['cancel_sale'])){
        /*将商品标记为未申请售后*/
        $sale_info = sale_info($service_id);
        foreach ($sale_info['goods'] as $key => $value) {
                $sql =  " UPDATE ".$ecs->table('order_goods').
                " SET is_sale = 0 ".
                " WHERE rec_id =$value[rec_id]";
                $db->query($sql);
        }
        /*查询该售后是否有退货单 是则删除退货单*/
        $sql = "SELECT return_id FROM ".$ecs->table('order_return_info')." WHERE service_id = $service_id ";
        $return_id = $db->getOne($sql);
        if(!empty($return_id)){
        /*删除退货单*/
        $sql = "DELETE FROM ".$ecs->table('order_return_info')." WHERE return_id = $return_id";
        $db->query($sql);
        /*删除退货单商品*/
        $sql = "DELETE FROM ".$ecs->table('order_return_goods')." WHERE return_id = $return_id";
        $db->query($sql);
        }
        /*查询是否有退款单*/
        $sql = "SELECT refund_id FROM ".$ecs->table('refund')." WHERE service_id = $service_id ";
        $refund_id = $db->getOne($sql);
        if (!empty($refund_id)) {
            /*删除退款单*/
            $sql = "DELETE FROM ".$ecs->table('refund')." WHERE service_id = $service_id";
            $db->query($sql);
        }
        /*修改售后状态*/
        $sql =  " UPDATE ".$ecs->table('sale_service').
                " SET service_state = 3 ,handle_state =8 ".
                " WHERE service_id =$service_id";
        $db->query($sql);
        //记录操作
        $handle_record = array(
        'handle_user'       => $_SESSION['admin_name'],
        'service_id'        => $service_id,
        'add_time'          => time(),
        'content'           => $content,
        'handle_id'         => 2,
        );
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
        $links[] = array('href' => 'sale.php?act=sale_list', 'text' => "操作成功");
        sys_msg("操作成功", 100, $links);
    }




}
/*AJAX修改售后内容*/
elseif ($_REQUEST['act'] == 'change') {
        include_once(ROOT_PATH . 'includes/cls_json.php');
        $json = new JSON();

        switch ($_REQUEST['step']) {
            /*修改处理方式*/
            case 'handle_type':
                $handle_type = !empty($_REQUEST['handle_type'])?$_REQUEST['handle_type']:'';
                $service_id = !empty($_REQUEST['service_id'])?$_REQUEST['service_id']:'';
                $sql =   " UPDATE ".$GLOBALS['ecs']->table('sale_service').
                         " set handle_type=$handle_type".
                         " WHERE service_id=$service_id";
                $db->query($sql);
                echo $json->encode(1);
                break;
            default:
                # code...
                break;
        }
}











function sale_list(){
        
        $filter['order_sn'] = !empty($_REQUEST['order_sn']) ?$_REQUEST['order_sn'] :'';
        $filter['service_state'] = !empty($_REQUEST['service_state']) ?$_REQUEST['service_state'] :'';
        $filter['service_type'] = !empty($_REQUEST['service_type']) ?$_REQUEST['service_type'] :'';
        $filter['handle_state'] = !empty($_REQUEST['handle_state']) ?$_REQUEST['handle_state'] :'';
        $where = 'WHERE 1 ';
        if(!empty($filter['order_sn'])){
            $where .= ' AND s.order_sn = '.$filter['order_sn'];
        }
        if(!empty($filter['service_state'])){
            $where .= ' AND s.service_state = '.$filter['service_state'];
        }
        if(!empty($filter['service_type'])){
            $where .= ' AND s.service_type = '.$filter['service_type'];
        }
        if(!empty($filter['handle_state'])){
            $where .= ' AND s.handle_state = '.$filter['handle_state'];
        }
        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        $sql=   " SELECT s.*,o.consignee AS name FROM ".$GLOBALS['ecs']->table('sale_service')."AS s ".
                " LEFT JOIN ".$GLOBALS['ecs']->table('order_info')." AS o ON o.order_sn = s.order_sn ".
                $where."  ORDER BY add_time DESC";
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql = $sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        $row = $GLOBALS['db']->getAll($sql);
        foreach ($row as $key => $value) {
            $row[$key]['add_time'] =date('Y-m-d-H:i:s',$value['add_time']);
        }
        $arr = array('sale_list' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}
/*获取售后订单信息*/
    function sale_info($service_id){
        //获取售后表信息
        $sql= "SELECT * FROM ".$GLOBALS['ecs']->table('sale_service') ." WHERE service_id =".$service_id;
        $row = $GLOBALS['db']->getRow($sql);
        $goods_list = array_filter(explode(",",$row['goods']));
        //重组商品数据
        $where="";
        foreach ($goods_list as $key => $value) {
            $rec_id = substr($value,0,strpos($value,"*"));
            $goods_number = substr($value,(strpos($value,"*")+1));
            $goods[$rec_id]=$goods_number;
            $where ="rec_id = ". $rec_id." OR ".$where;
        }
         $where =substr($where,0,-3); 
         //获取商品信息
         $sql ="SELECT * FROM ".$GLOBALS['ecs']->table('order_goods') ."WHERE ".$where;
         $order_goods = $GLOBALS['db']->getAll($sql);
         foreach ($order_goods as $key => $value) {
             foreach ($goods as $keys => $goods_number) {
                 if ($keys == $value['rec_id']) {
                     $order_goods[$key]['goods_number']=$goods_number;
                 }
             }
         }
         //获取操作记录
         $sql = " SELECT * FROM ".$GLOBALS['ecs']->table('handle_record') .
                " WHERE service_id =".$service_id.
                " ORDER BY add_time DESC";
         $handle_record = $GLOBALS['db']->getAll($sql);
         foreach ($handle_record as $key => $value) {
             $handle_record[$key]['add_time']=date("Y-m-d H:i:s",$value['add_time']);
         }
         //重组售后信息
         $row['goods']=$order_goods;
         $row['handle_record']=$handle_record;


         return $row;
    }




 ?>